package config

import (
	"fmt"
	"os"

	"github.com/BurntSushi/toml"
)

var (
	// Cfg define global config.
	Cfg *GlobalCfg
	// confPath define config_prod.toml path.
	confPath = "config.toml"
)

// GlobalCfg define global configs.
type GlobalCfg struct {
	Title        string `toml:"title"`
	ListenPort   string `toml:"listen_port"`
	SelfDownload bool   `toml:"self_download"`
	Debug        bool   `toml:"debug"`
	AuthKey      string `toml:"auth_key"`
	MySQL        MySQL  `toml:"mysql"`
}

// GetGlobalCfg use to get global configs.
func GetGlobalCfg() *GlobalCfg {
	if Cfg == nil {
		Cfg = &GlobalCfg{}
		if err := update(); err != nil {
			panic(err)
		}
		return Cfg
	}
	return Cfg
}

// Update update config from toml file.
func update() error {
	dir, err := os.Getwd()
	if err != nil {
		return err
	}

	_, err = toml.DecodeFile(fmt.Sprintf("%s/%s", dir, confPath), Cfg)
	if err != nil {
		return err
	}
	return nil
}
